package org.example.partnerbacked.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
<<<<<<< HEAD
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
=======
>>>>>>> 515eae65c6ba5dc43fc118901c72b817d3b49dba
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
<<<<<<< HEAD

=======
import jakarta.annotation.Resource;
>>>>>>> 515eae65c6ba5dc43fc118901c72b817d3b49dba
import jakarta.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.example.partnerbacked.common.ErrorCode;
import org.example.partnerbacked.config.ConfigSession;
import org.example.partnerbacked.config.UserConstant;
import org.example.partnerbacked.exception.BusinessException;
import org.example.partnerbacked.model.User;
import org.example.partnerbacked.service.UserService;
import org.example.partnerbacked.mapper.UserMapper;
<<<<<<< HEAD
import org.springframework.beans.factory.annotation.Autowired;
=======
>>>>>>> 515eae65c6ba5dc43fc118901c72b817d3b49dba
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;

import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import static org.example.partnerbacked.config.ConfigSession.USER_LOGIN_STATE;

/**
* @author 70556
* @description 针对表【user(用户)】的数据库操作Service实现
* @createDate 2024-12-02 11:15:27
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService{
<<<<<<< HEAD
    @Autowired
    private UserMapper userMapper;
=======
    @Resource
    private  UserMapper userMapper;
>>>>>>> 515eae65c6ba5dc43fc118901c72b817d3b49dba
    private static final String SALT = "partner";
    @Override
    public User userLogin(String userAccount, String userPassword, HttpServletRequest request) {
        if(StringUtils.isAnyBlank(userAccount,userPassword)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"参数为空");
        }
        QueryWrapper<User> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("userAccount",userAccount);
          User user = userMapper.selectOne(queryWrapper);
<<<<<<< HEAD
        if(user==null){
=======
        if(user!=null){
>>>>>>> 515eae65c6ba5dc43fc118901c72b817d3b49dba
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"账号不存在");
        }
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT+userPassword).getBytes());
        if(!encryptPassword.equals(userMapper.selectOne(queryWrapper).getUserPassword())){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"密码错误");
        }
        // 创建Session
        // 3. 用户脱敏
        User safetyUser = getSafetyUser(user);
        // 4. 记录用户的登录态
        request.getSession().setAttribute(ConfigSession.USER_LOGIN_STATE, safetyUser);
        return safetyUser;
    }
    @Override
    public User getSafetyUser(User user) {
        user.setUserPassword(null);
        return user;
    }

    @Override
    public boolean isAdmin(HttpServletRequest request) {
        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
        User user = (User) userObj;
        return user != null && user.getUserRole() == UserConstant.ADMIN_ROLE;
    }

    @Override
    public List<User> searchUsersByTags(List<String> tagNameList) {
        if(CollectionUtils.isEmpty(tagNameList)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        List<User> userList = userMapper.selectList(queryWrapper);
        Gson gson = new Gson();
        return userList.stream().filter(user -> {
            String tagsStr = user.getTags();
            Set<String> tagSet = gson.fromJson(tagsStr, new TypeToken<Set<String>>() {}.getType());
            for(int i = 0; i < tagNameList.size(); i++){
                if(!tagSet.contains(tagNameList.get(i))){
                    return false;
                }
            }
           return true;
        }).map(this::getSafetyUser).collect(Collectors.toList());
    }

    @Override
    public int updateUser(User user, HttpServletRequest request) {
        long userId = user.getId();
        if (userId <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = (User) request.getSession().getAttribute(USER_LOGIN_STATE);
        // todo 补充校验，如果用户没有传任何要更新的值，就直接报错，不用执行 update 语句
        // 如果是管理员，允许更新任意用户
        // 如果不是管理员，只允许更新当前（自己的）信息
        if (!isAdmin((request)) && userId != loginUser.getId()) {
            throw new BusinessException(ErrorCode.NO_AUTH);
        }
        User oldUser = userMapper.selectById(userId);
        if (oldUser == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        return userMapper.updateById(user);
    }

    @Override
    public List<User> matchUsers(long num, HttpServletRequest request) {
        return List.of();
    }

    @Override
<<<<<<< HEAD
    public Page<User> recommendUsers(long pageSize, long pageNum, HttpServletRequest request) {
        return null;
    }

    @Override
=======
>>>>>>> 515eae65c6ba5dc43fc118901c72b817d3b49dba
    public long userRegister(String userAccount, String userPassword, String checkPassword, String planetCode) {

           if(!userPassword.equals(checkPassword)) {
               throw new BusinessException(ErrorCode.PARAMS_ERROR, "两次密码不一致");
           }
           if(userPassword.length()<4||userPassword.length()>10){
               throw new BusinessException(ErrorCode.PARAMS_ERROR, "密码长度不符合要求");
           }
           if(planetCode.length()<5){
               throw new BusinessException(ErrorCode.PARAMS_ERROR, "星球编号长度不符合要求");
           }
        String validPattern = "[`~!@#$%^&*()+=|{}':;',\\\\[\\\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
        Matcher matcher = Pattern.compile(validPattern).matcher(userAccount);
        if(matcher.find()){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号含有特殊字符");
        }
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount",userAccount);
<<<<<<< HEAD
        long count =userMapper.selectCount(queryWrapper);
        if(count>0){
=======
        if(userMapper.selectOne(queryWrapper)!=null){
>>>>>>> 515eae65c6ba5dc43fc118901c72b817d3b49dba
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号重复");
        }
        queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("planetCode",planetCode);
        if(userMapper.selectOne(queryWrapper)!=null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "星球编号重复");
        }
        User user = new User();
        user.setUserAccount(userAccount);
        user.setUserPassword(userPassword);
        user.setPlanetCode(planetCode);
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT+userPassword).getBytes());
          user.setUserPassword(encryptPassword);
         Boolean result =  this.save(user);
        if (!result) {
            return -1;
        }
        return user.getId();
    }

    @Override
    public int userLogout(HttpServletRequest request) {
        request.removeAttribute(USER_LOGIN_STATE);
        return 1;
    }

}




